# !/usr/bin/env Python
# -*- coding:utf-8 -*-
# task_51_memo.py
# A memo demo 51备忘录，用sys模块添加系统参数
# author: luoxiang

from color_me import ColorMe  # 导入4种颜色的自建模块
import time  # 导入时间模块
import sys  # 导入系统模块
import re


RE_USER_INFO = {}
USER_INFO = {'luoxiang': {'昵称': 'luoxiang', '真实姓名': '罗翔', '身份证号': '533001199107236616', '电话': '13987054232', '邮箱': '634354682@qq.com', '密码': 'luoxiang666666'}}
PERSONAL_INFO = {}



all_memo = []  # 新建备忘录列表，存储备忘信息
all_time = 0


def cycle_memo():
    '''循环备忘录'''
    try:
        is_add = True
        while(is_add):  # 判断真假开始循环
            input_memo()
            print('（y：继续添加，n: 退出）')  # 判断是否继续循环
            is_add = input().strip() == 'y'

    except Exception as e:
        print('循环函数错误！', e)


def login():
    '''用户登录和注册界面
       用正则表达式定义用户信息'''

    #定义用户信息规则
    RE_NICKNAME = re.compile(r'[a-zA-Z0-9]\w+')
    RE_REALNAME = re.compile(r'^[\u4e00-\u9fa5]{2,4}$')
    RE_IDCARD = re.compile(r'^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$')  # 18位身份证对象
    RE_PHONE = re.compile(r'13\d\d{8}|14[5,7,9]\d{8}|15[0,1,2,3,5,6,7,8,9]\d{8}|166\d{8}|17[1,2,3,5,6,7,8]\d{8}|18\d{8}|19[8,9]\d{8}|\d{3}-\d{8}|\d{4}-\d{7}')  # 电话对象
    RE_EMAIL = re.compile(r'^[\da-z]+([\-\.\_]?[\da-z]+)*@[\da-z]+([\-\.]?[\da-z]+)*(\.[a-z]{2,})+$')  # 邮箱对象
    RE_PASSWORD = re.compile(r'^[a-zA-Z]\w{7,17}$')

    # 定义用户信息规则字典
    RE_USER_INFO['昵称'] = RE_NICKNAME
    RE_USER_INFO['真实姓名'] = RE_REALNAME
    RE_USER_INFO['身份证号'] = RE_IDCARD
    RE_USER_INFO['电话'] = RE_PHONE
    RE_USER_INFO['邮箱'] = RE_EMAIL
    RE_USER_INFO['密码'] = RE_PASSWORD
    try:
        print('欢迎使用51备忘录'.center(30, '-'))
        time.sleep(1)
        choice = input("用户登录请按1，实名注册请按2:")
        if choice == '1':
            while True:
                print('用户登录'.center(30, '-'))
                login = input('用户昵称:')
                if login in USER_INFO.keys():
                    num = 0
                    while True:
                        password = input('输入密码：')
                        if password == USER_INFO[login]['密码']:
                            print("登录成功！")
                            return False
                        else:
                            num += 1
                            if num == 3:
                                print(f'密码错误{num}次，账号锁定，请查证后再登录')
                                return False
                            else:
                                print(f'密码错误{num}次，请重新输入：')
                            continue
                else:
                    print("输入错误，请重新输入")
                    continue

        if choice == '2':
            print('用户注册'.center(30, '-'))
            time.sleep(1)
            print('请按要求填写注册信息(必填)：')
            time.sleep(1)
            print('昵称：必须由26个大小写字母和数字组成')
            time.sleep(1)
            print('真实姓名：汉字，需要和身份证姓名一致')
            time.sleep(1)
            print('身份证号：18位数字组成')
            time.sleep(1)
            print('邮箱：用户本人正在使用的有效邮箱')
            time.sleep(1)
            print('密码：首位必须为字母，密码长度8-18位')
            is_add = True
            while (is_add):
                for key_CH, re_obj in RE_USER_INFO.items():
                    login = input(f'{key_CH}:')
                    result = re_obj.match(login)  
                    if result:
                        PERSONAL_INFO[key_CH] = result.group()
                    else:
                        while True:
                            print('格式错误，请重新输入')
                            login = input(f'{key_CH}:')
                            result = re_obj.match(login)  
                            if result:
                                PERSONAL_INFO[key_CH] = result.group()
                                break
                            else:
                                continue

                if len(PERSONAL_INFO) == 6:
                    # USER_INFO字典用来存储和调用用户信息
                    USER_INFO[PERSONAL_INFO['昵称']] = PERSONAL_INFO
                    print(f'''用户{PERSONAL_INFO['昵称']}注册信息：{PERSONAL_INFO}''')
                    print(f'注册成功！已注册用户{len(USER_INFO)}名:{USER_INFO.keys()}')
                    print('y:继续注册，n：登录备忘录')
                    is_add = input().strip() == 'y'

    except Exception as e:
        print('登录函数错误！', e)


def input_memo():
    '''备忘信息录入界面'''
    try:
        print('备忘信息录入'.center(30, '-'))
        # 添加两个备忘录输入格式事例
        print('示例1：2019年07月08日8点30分去单位上班，用时3h30min')
        time.sleep(1)
        print('示例2：07月08日上午需要带笔记本电脑去上班')
        time.sleep(1)
        in_sentence = input('请按照示例格式输入：')
        split_memo(in_sentence)

    except Exception as e:
        print('录入函数错误！', e)


def split_memo(in_sentence):
    '''判断拆解备忘录信息'''
    RE_DATE = re.compile(r'\d{4}?年\d{1,2}月\d{1,2}日')
    RE_TIME = re.compile(r'\d{1,2}点\d{1,2}分|早晨|上午|中午|下午|傍晚|晚上|深夜|凌晨')
    RE_THING = re.compile(r'')
    
    try:
        # 用时间字典定义8个时间段
        time_dict = {'早晨': '6点到8点', '上午': '9点到11点',
                     '中午': '12点到14点', '下午': '15点到17点',
                     '傍晚': '18点到20点', '晚上': '21点到23点',
                     '深夜': '0点到2点', '凌晨': '3点到5点'}

        # 根据输入格式，判断拆分信息（日期，时点，事件，时长）形式
        if in_sentence[in_sentence.find('日') + 1:
                       in_sentence.find('日') + 3]in time_dict.keys():
            in_date = in_sentence[:in_sentence.find('日') + 1]
            in_time = time_dict[in_sentence[in_sentence.find('日') + 1:
                                in_sentence.find('日') + 3]]
            in_thing = in_sentence[in_sentence.find('日') + 3:]
            in_duration = '3h'  # 每个时间副词，默认用时3小时
            hours = 3  # 每个时间副词，默认用时3小时
            minutes = 0

        else:
            in_date = in_sentence[:in_sentence.find('日') + 1]
            in_time = in_sentence[
                in_sentence.find('日') + 1: in_sentence.find('分') + 1]
            in_thing = in_sentence[
                in_sentence.find('分') + 1: in_sentence.find('，')]
            in_duration = in_sentence[in_sentence.find('时') + 1:]
            hours = in_sentence[in_sentence.find('时') + 1:
                                in_sentence.find('h')]
            minutes = in_sentence[in_sentence.find('h') + 1:
                                  in_sentence.find('m')]

        add_memo(in_date, in_time, in_thing, in_duration)
        print_memo(hours, minutes)

    except Exception as e:
        print('拆解函数错误！', e)


def add_memo(in_date, in_time, in_thing, in_duration):
    '''添加备忘信息'''
    try:
        # 新建事件信息字典，并将四种信息键和值依次存入字典
        things_dict = {}
        things_dict['date'] = in_date
        things_dict['time'] = in_time
        things_dict['thing'] = in_thing
        things_dict['duration'] = in_duration
        all_memo.append(things_dict)  # 将每条新建的字典信息，追加到备忘录列表
        colour_memo(all_memo)
    except Exception as e:
        print('添加函数错误！', e)


def colour_memo(all_memo):
    '''给不同拆分信息上色并打印输出'''
    try:
        
        num = 0  # 新建序号
        print(('备忘信息列表').center(30, '-'))
        time.sleep(1)
        for m in all_memo:  # 将列表信息逐条输出
            num += 1  # 追加序号

            # 给四种信息添加不同颜色，并输出
            # vscode上本人没安装运行颜色的扩展，输出不了颜色
            date_color = ColorMe('日期:' + m['date']).red()
            time_color = ColorMe('时点:' + m['time']).green()
            thing_color = ColorMe('事件:' + m['thing']).blue()
            duration_color = ColorMe('时长:' + m['duration']).yellow()
            print(f'{num}.{date_color}, {time_color},',
                  f'{thing_color}, {duration_color}')
            time.sleep(1)

    except Exception as e:
        print('上色函数错误！', e)


def print_memo(hours, minutes):
    '''统计输出备忘信息条数和时长'''
    try:
        global all_time
        all_time += int(hours) * 60 + int(minutes)  # 通过运算，追加总时长
        print(f'共{len(all_memo)}条备忘信息,',
              f'总时长：{all_time // 60}小时{all_time % 60}分。', end='')
        time.sleep(1)
        
    except Exception as e:
        print('统计输出函数错误！', e)


def delete_memo():
    '删除备忘记录'
    print('待开发。。。')


def modify_memo():
    '更改备忘记录'
    print('待开发。。。')


def query_memo():
    '查询备忘记录'
    print('待开发。。。')

def help_memo():
    '''提示用法'''
    print('usage：')
    print('-h, -help 帮助')
    time.sleep(1)
    print('-a, --add 添加记录')
    time.sleep(1)  
    print('-d, --delete 删除记录')
    time.sleep(1)
    print('-m, --modify 修改记录')
    time.sleep(1)
    print('-q, --query 查询记录')


def main():
    '''
    main: 程序主入口，当前文件单独运行时候从这里运行
    函数优化：每个函数尽量只干一件事！（前提是每个函数都能正常运行）
    用sys模块添加系统参数
    '''
    try:
        login()
        if len(sys.argv) == 1:
            help_memo()
            time.sleep(1)
        usage = input('用法输入：')
        sys.argv.append(usage)
        print(sys.argv)
        if sys.argv[1] in {'-h', '--help'}:
            help_memo()
        elif sys.argv[1] in {'-a', '--add'}:
            input_memo()
        elif sys.argv[1] in {'-d', '--delete'}:
            delete_memo()
        elif sys.argv[1] in {'-m', '--modify'}:
            modify_memo()
        elif sys.argv[1] in {'-q', '--query'}:
            query_memo()
        else:
            help()

    except Exception as e:
        print('memo程序错误！', e)

if __name__ == '__main__':
    main()
